from django.db                   import transaction
from django.db.models            import signals,get_models
from django.utils.datastructures import SortedDict
from sitepal.sitebase            import models as sitebase_app
from sitepal.sitebase.managers   import ResourceManager
from sitepal.sitebase.models     import Property

_resource_managers = SortedDict()
def register_manager(manager,submodule=None):
    global _resource_managers
    assert isinstance(manager,ResourceManager)
    assert isinstance(submodule,basestring) or submodule is None
    if manager not in _resource_managers:
        _resource_managers[manager] = set()
    if submodule:
        _resource_managers[manager].add(submodule)

register_manager(Property.objects)

@transaction.commit_on_success
def sync_managers(sender,created_models,verbosity=2,**kwargs):
    global _resource_managers
    for manager,submodules in _resource_managers.iteritems():
        if verbosity == 1:
            print u"synching {0}".format(manager.model._meta.verbose_name)
        manager.sync_prepare()
        manager.sync_database()
        for submodule in submodules:
            manager.sync_database(submodule)

signals.post_syncdb.connect(sync_managers,sender=sitebase_app)

@transaction.commit_on_success
def create_permissions(app,created_models,verbosity,**kwargs):
    from django.contrib.auth.models         import Permission
    from django.contrib.contenttypes.models import ContentType
    from sitepal.sitebase.models            import Entity,Tree,Access
    
    app_model_classes = get_models(app)
    if not app_model_classes:
        return
    for model_class in app_model_classes:
        ctype = ContentType.objects.get_for_model(model_class)
        opts  = model_class._meta
        args  = []
        args.append((u"read_{0}",u"Can read {0}"))
        if not issubclass(model_class,Access):
            args.append((u"grant_{0}_access",u"Can grant {0} access"))
        if issubclass(model_class,Entity):
            args.append((u"take_{0}_ownership",u"Can take {0} ownership"))
            if issubclass(model_class,Tree):
                args.append((u"grant_{0}_inheritable_access",u"Can grant {0} inheritable access"))
        for codename,name in args:
            codename   = codename.format(opts.object_name.lower())
            name       = name.format(opts.verbose_name_raw)
            p, created = Permission.objects.get_or_create(codename=codename,content_type__pk=ctype.id,
                                                          defaults={'name': name,'content_type': ctype})
            if created and verbosity >= 2:
                print "Adding permission '{0}'".format(p)

signals.post_syncdb.connect(create_permissions)
